package com.adv.ems.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.adv.ems.constants.EmsConst;
import com.adv.ems.db.entity.ReportHourPoolDO;
import com.adv.ems.db.entity.SystemConfigDO;
import com.adv.ems.filters.FilterFactory;
import com.adv.ems.filters.report.dto.ReportHourPoolDTO;
import com.adv.ems.manager.*;
import com.adv.ems.model.dto.ReportDataDealConfigDTO;
import com.adv.ems.model.vo.ResultVO;
import com.adv.ems.service.EnergyReportDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class EnergyReportDataServiceImpl implements EnergyReportDataService, SmartInitializingSingleton {
    @Resource SystemConfigManager systemConfigManager;
    @Resource ReportHourPoolManager reportHourPoolManager;
    @Resource
    FilterFactory<ReportHourPoolDTO, Boolean> filterFactory;

    @Override
    public ResultVO<Boolean> begin() {
        ResultVO<Boolean> resultVO;
        ReportDataDealConfigDTO config = getReportDataDealConfig();
        log.info("累积数据报表------开始【delay:{},size:{}】", config.getUpdateDelayMinute(), config.getPullDataSize());
        List<ReportHourPoolDO> reportHours = reportHourPoolManager.getRecentUnUpdateHourAndDel(config.getUpdateDelayMinute(), config.getPullDataSize());
        if (reportHours.isEmpty()) {
            resultVO = ResultVO.success(false);
        }else {
            List<ReportHourPoolDTO> collect = reportHours.stream().map(ReportHourPoolDTO::from).collect(Collectors.toList());
            log.info("累积数据报表------前置处理");
            filterFactory.doBeforeFilter(collect);
            log.info("累积数据报表------后置处理");
            filterFactory.doAfterFilter(collect);
            resultVO = ResultVO.success(true);
        }
        log.info("累积数据报表------结束【total:{}】", reportHours.size());
        return resultVO;
    }

    private ReportDataDealConfigDTO getReportDataDealConfig() {
        List<SystemConfigDO> configs = systemConfigManager.selectByType(EmsConst.SystemConfigKey.SYSTEM_CONFIG_REPORT_DATA_DEAL_CONFIG_KEY);
        if (CollectionUtil.isEmpty(configs)) {
            return new ReportDataDealConfigDTO();
        }
        return JSONUtil.toBean(JSONUtil.toJsonStr(configs.get(0).getValue()), ReportDataDealConfigDTO.class);
    }

    @Override
    public void afterSingletonsInstantiated() {
    }
}
